const fs = require('fs')
const path = require('path')
const Axios = require('axios')
const superagent = require('superagent')
const request = require('request')

function mkdirSync(dirname) {
  if (fs.existsSync(dirname)) {
    return true
  } else {
    if (mkdirSync(path.dirname(dirname))) {
      fs.mkdirSync(dirname)
      return true
    }
  }
  return false
}

// 使用request 或者 superagent
function downloadFile(urlList) {
  const imagesDir = './public/images/'
  for (const url of urlList) {
    const name = url.slice(url.lastIndexOf('/') + 1)

    if (mkdirSync(imagesDir)) {
      // request(url).pipe(fs.createWriteStream(imagesDir + name))
      superagent.get(url).pipe(fs.createWriteStream(imagesDir + name))
    }
  }
}
downloadFile([
  'http://images2015.cnblogs.com/blog/138012/201610/138012-20161022224402576-1611337354.png',
  'https://github.com/GoogleChrome/puppeteer/blob/master/README.md'
])

// 使用axios
async function fileLoader(url, dir) {
  const name = url.slice(url.lastIndexOf('/') + 1)
  const imagesDir = dir ? dir : `/public/${new Date().toLocaleDateString()}/`
  const filePath = imagesDir + name
  if (mkdirSync(imagesDir)) {
    const writer = fs.createWriteStream('./' + filePath)
    const response = await Axios({
      url,
      method: 'GET',
      responseType: 'stream'
    })
    response.data.pipe(writer)
    return new Promise((resolve, reject) => {
      writer.on('finish', () => resolve(filePath)) //  createWriteStream finish 事件无参数返回
      writer.on('error', reject)
    })
  }
}
// fileLoader(
//   'http://images2015.cnblogs.com/blog/138012/201610/138012-20161022224402576-1611337354.png'
// )
// fileLoader(
//   'https://github.com/GoogleChrome/puppeteer/blob/master/README.md'
// ).then(rs => console.log(rs))
